package com.rabbit.demo.ylr.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


/**
 * @ClassName producer
 * @Description TODO
 * @Author 11
 * @Date 2021/7/14 11:06
 * @Version 1.0
 */
public class Producer {

    public static void main(String[] args) {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //2 设置连接属性
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        Connection connection =null;
        Channel channel=null;

        //3 从连接工厂中获取连接
        try {
            connection = connectionFactory.newConnection("生产者");
            // 4 连接中获取通道
            channel = connection.createChannel();
            //5 申明队列queue存储消息
//            channel.queueDeclare("queue1",false,false,false,null);

            channel.exchangeDeclare("direct-exchange","direct");



            // 6 准备发送消息的内容
            String massage = "你好，direct";

            String massage1 = massage +"我是key1";
            String massage2 = massage +"我是key2";

            // 7 发送消息给mq-server
            String exchangeName = "direct-exchange";
            String routingKey1="testkey1";
            String routingKey2="testkey2";

            channel.basicPublish("direct-exchange",routingKey1,null,massage1.getBytes());
            channel.basicPublish("direct-exchange",routingKey2,null,massage2.getBytes());
            System.out.println("消息发送成功");









        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常！");
        }finally {
            // 8 释放连接
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
}
